package com.yunquan.ohana.utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.net.wifi.WifiNetworkSpecifier
import android.os.Build
import android.util.Log

object WifiUtils {
    /**
     * 连接到指定 Wi-Fi 网络
     * @param context 上下文
     * @param ssid Wi-Fi 名称
     * @param password Wi-Fi 密码
     */
    fun connectToWiFi(context: Context, ssid: String, password: String) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10 及以上使用 WifiNetworkSpecifier
            val wifiSpecifier = WifiNetworkSpecifier.Builder()
                .setSsid(ssid)
                .setWpa2Passphrase(password)
                .build()

            val networkRequest = NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .setNetworkSpecifier(wifiSpecifier)
                .build()

            val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val networkCallback = object : ConnectivityManager.NetworkCallback() {
                override fun onAvailable(network: Network) {
                    super.onAvailable(network)
                    connectivityManager.bindProcessToNetwork(network)
                    Log.d("WiFiHelper", "Wi-Fi 连接成功: $ssid")
                }
            }
            connectivityManager.requestNetwork(networkRequest, networkCallback)
        } else {
            // Android 9 及以下使用 WifiConfiguration
            val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

            // 开启 Wi-Fi（如果 Wi-Fi 关闭）
            if (!wifiManager.isWifiEnabled) {
                wifiManager.isWifiEnabled = true
            }

            val wifiConfig = android.net.wifi.WifiConfiguration()
            wifiConfig.SSID = "\"$ssid\""
            wifiConfig.preSharedKey = "\"$password\""

            val netId = wifiManager.addNetwork(wifiConfig)
            wifiManager.disconnect()
            wifiManager.enableNetwork(netId, true)
            wifiManager.reconnect()

            Log.d("WiFiHelper", "尝试连接 Wi-Fi: $ssid")
        }
    }

    /**
     * 获取当前连接的 Wi-Fi 信息
     * @param context 上下文
     * @return 当前 Wi-Fi SSID 或 "未连接 Wi-Fi"
     */
    fun getCurrentWiFiInfo(context: Context): WifiInfo? {
        L.d("检测当前WIFI链接")
        val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val wifiInfo: WifiInfo = wifiManager.connectionInfo
        return if (wifiInfo.ssid != null && wifiInfo.ssid != "<unknown ssid>") {
            wifiInfo
        } else {
            null // "未连接 Wi-Fi"
        }
    }
}